<template>
  <div class="multi-domain-property-manager">
    <div class="manager-header">
      <h2>多领域属性管理</h2>
      <div class="header-actions">
        <Button type="primary" @click="saveAllDomains" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存所有领域
        </Button>
        <Button @click="exportConfig">
          <IconifyIcon icon="ant-design:export-outlined" />
          导出配置
        </Button>
      </div>
    </div>

    <DomainSelector
      :domains="domainConfigs"
      :active-domain="activeDomain"
      :field-counts="fieldCounts"
      @domain-change="handleDomainChange"
    />

    <div class="domain-content">
      <div class="domain-header">
        <div class="domain-info">
          <h3>{{ currentDomainConfig.name }}</h3>
          <p>{{ currentDomainConfig.description }}</p>
          <div class="domain-stats">
            <Tag color="blue"
              >字段数: {{ getDomainFieldCount(activeDomain) }}</Tag
            >
            <Tag color="green"
              >必填: {{ getDomainRequiredCount(activeDomain) }}</Tag
            >
            <Tag color="orange"
              >可选: {{ getDomainOptionalCount(activeDomain) }}</Tag
            >
          </div>
        </div>
        <div class="domain-actions">
          <Button type="primary" @click="addField">
            <IconifyIcon icon="ant-design:plus-outlined" />
            添加字段
          </Button>
          <Button @click="previewDomainForm">
            <IconifyIcon icon="ant-design:eye-outlined" />
            预览表单
          </Button>
        </div>
      </div>

      <div class="fields-section">
        <div class="fields-list">
          <div
            v-for="(field, index) in getDomainFields(activeDomain)"
            :key="field.id"
            class="field-item"
            :class="{ 'field-item--selected': selectedFieldId === field.id }"
            @click="selectField(field.id)"
          >
            <div class="field-info">
              <div class="field-header">
                <IconifyIcon :icon="getFieldTypeIcon(field.component)" />
                <span class="field-name">{{ field.label }}</span>
                <Tag :color="getFieldTypeColor(field.component)">
                  {{ getFieldTypeName(field.component) }}
                </Tag>
                <Tag v-if="field.rules === 'required'" color="red">必填</Tag>
              </div>
              <div class="field-details">
                <span>字段名: {{ field.fieldName }}</span>
                <span v-if="field.componentProps?.placeholder">
                  占位符: {{ field.componentProps.placeholder }}
                </span>
              </div>
            </div>
            <div class="field-actions">
              <Button type="link" size="small" @click.stop="editField(index)">
                <IconifyIcon icon="ant-design:edit-outlined" />
                编辑
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click.stop="removeField(index)"
              >
                <IconifyIcon icon="ant-design:delete-outlined" />
                删除
              </Button>
            </div>
          </div>
        </div>

        <div class="field-editor" v-if="selectedField">
          <FieldEditor
            :field="selectedField"
            @update="updateField"
            @delete="deleteSelectedField"
          />
        </div>
      </div>
    </div>

    <!-- 字段编辑器模态框 -->
    <Modal
      :visible="fieldEditorVisible"
      title="字段配置"
      width="600px"
      :footer="null"
      :destroyOnClose="true"
      @update:visible="fieldEditorVisible = $event"
    >
      <FieldEditor
        v-if="editingField"
        :field="editingField"
        @update="updateEditingField"
        @cancel="fieldEditorVisible = false"
      />
    </Modal>

    <!-- 领域表单预览模态框 -->
    <Modal
      :visible="previewVisible"
      :title="`${currentDomainConfig.name} 表单预览`"
      width="900px"
      :footer="null"
      :destroyOnClose="true"
      @update:visible="previewVisible = $event"
    >
      <PropertyFormPreview
        v-if="previewVisible"
        :schema="previewSchema"
        :data="previewData"
        @form-change="handlePreviewFormChange"
      />
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { Button, Modal, Tag, message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import {
  PropertyDomain,
  FieldComponent,
} from '../../../../api/resource-center/types';
import type {
  FieldSchema,
  DomainConfig,
  MultiDomainProperties,
} from '../../../../api/resource-center/types';

import DomainSelector from './DomainSelector.vue';
import FieldEditor from './FieldEditor.vue';
import PropertyFormPreview from './PropertyFormPreview.vue';

interface Props {
  resourceId: string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  'properties-update': [properties: MultiDomainProperties];
}>();

// 响应式数据
const saving = ref(false);
const activeDomain = ref<PropertyDomain>(PropertyDomain.BUSINESS);
const selectedFieldId = ref('');
const fieldEditorVisible = ref(false);
const editingField = ref<FieldSchema | null>(null);
const previewVisible = ref(false);
const previewSchema = ref<FieldSchema[]>([]);
const previewData = ref<Record<string, any>>({});

// 多领域属性数据
const multiDomainProperties = ref<MultiDomainProperties>({
  domains: {
    [PropertyDomain.BUSINESS]: {
      schema: [],
      data: {},
      config: getDefaultDomainConfig(PropertyDomain.BUSINESS),
    },
    [PropertyDomain.OPERATION]: {
      schema: [],
      data: {},
      config: getDefaultDomainConfig(PropertyDomain.OPERATION),
    },
    [PropertyDomain.TECHNICAL]: {
      schema: [],
      data: {},
      config: getDefaultDomainConfig(PropertyDomain.TECHNICAL),
    },
    [PropertyDomain.COMPLIANCE]: {
      schema: [],
      data: {},
      config: getDefaultDomainConfig(PropertyDomain.COMPLIANCE),
    },
  },
  metadata: {
    domainCount: 4,
    lastModified: new Date().toISOString(),
    modifiedBy: '',
    totalFields: 0,
    version: '1.0.0',
  },
});

// 加载模拟数据
const loadMockData = async () => {
  try {
    // 直接使用模拟数据，避免API调用问题
    const mockData = {
      domains: {
        [PropertyDomain.BUSINESS]: {
          schema: [
            {
              id: 'business_1',
              fieldName: 'building_type',
              label: '建筑类型',
              component: FieldComponent.SELECT,
              componentProps: {
                placeholder: '请选择建筑类型',
                options: [
                  { label: '酒店', value: '酒店' },
                  { label: '公寓', value: '公寓' },
                  { label: '办公楼', value: '办公楼' },
                ],
              },
              rules: 'required',
              defaultValue: '酒店',
              domain: PropertyDomain.BUSINESS,
              order: 1,
              isActive: true,
            },
            {
              id: 'business_2',
              fieldName: 'floors',
              label: '楼层数',
              component: FieldComponent.INPUT_NUMBER,
              componentProps: {
                placeholder: '请输入楼层数',
                min: 1,
                max: 200,
                addonAfter: '层',
              },
              rules: 'required',
              defaultValue: 25,
              domain: PropertyDomain.BUSINESS,
              order: 2,
              isActive: true,
            },
          ],
          data: {
            building_type: '酒店',
            floors: 25,
          },
          config: getDefaultDomainConfig(PropertyDomain.BUSINESS),
        },
        [PropertyDomain.OPERATION]: {
          schema: [
            {
              id: 'operation_1',
              fieldName: 'channel_status',
              label: '渠道状态',
              component: FieldComponent.SWITCH,
              componentProps: {
                checkedChildren: '上架',
                unCheckedChildren: '下架',
              },
              rules: 'required',
              defaultValue: true,
              domain: PropertyDomain.OPERATION,
              order: 1,
              isActive: true,
            },
          ],
          data: {
            channel_status: true,
          },
          config: getDefaultDomainConfig(PropertyDomain.OPERATION),
        },
        [PropertyDomain.TECHNICAL]: {
          schema: [
            {
              id: 'technical_1',
              fieldName: 'api_version',
              label: 'API版本',
              component: FieldComponent.INPUT,
              componentProps: {
                placeholder: '请输入API版本号',
              },
              rules: 'required',
              defaultValue: 'v1.0.0',
              domain: PropertyDomain.TECHNICAL,
              order: 1,
              isActive: true,
            },
          ],
          data: {
            api_version: 'v1.0.0',
          },
          config: getDefaultDomainConfig(PropertyDomain.TECHNICAL),
        },
        [PropertyDomain.COMPLIANCE]: {
          schema: [
            {
              id: 'compliance_1',
              fieldName: 'certification_status',
              label: '认证状态',
              component: FieldComponent.SELECT,
              componentProps: {
                placeholder: '请选择认证状态',
                options: [
                  { label: '已认证', value: 'certified' },
                  { label: '认证中', value: 'certifying' },
                  { label: '未认证', value: 'uncertified' },
                ],
              },
              rules: 'required',
              defaultValue: 'certified',
              domain: PropertyDomain.COMPLIANCE,
              order: 1,
              isActive: true,
            },
          ],
          data: {
            certification_status: 'certified',
          },
          config: getDefaultDomainConfig(PropertyDomain.COMPLIANCE),
        },
      },
      metadata: {
        version: '1.0.0',
        lastModified: new Date().toISOString(),
        modifiedBy: 'admin',
        domainCount: 4,
        totalFields: 5,
      },
    };

    multiDomainProperties.value = mockData;
    message.success('多领域属性数据加载成功');
  } catch (error) {
    console.error('加载多领域属性数据失败:', error);
    message.error('加载数据失败，使用默认配置');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadMockData();
});

// 计算属性
const domainConfigs = computed(() =>
  Object.values(multiDomainProperties.value.domains).map(
    (domain) => domain.config,
  ),
);

const currentDomainConfig = computed(
  () => multiDomainProperties.value.domains[activeDomain.value].config,
);

const fieldCounts = computed(() => {
  const counts: Record<PropertyDomain, number> = {} as any;
  Object.entries(multiDomainProperties.value.domains).forEach(
    ([domain, data]) => {
      counts[domain as PropertyDomain] = data.schema.length;
    },
  );
  return counts;
});

const selectedField = computed(() => {
  const fields = getDomainFields(activeDomain.value);
  return fields.find((field) => field.id === selectedFieldId.value);
});

// 方法
const getDomainFields = (domain: PropertyDomain): FieldSchema[] => {
  return multiDomainProperties.value.domains[domain].schema;
};

const getDomainFieldCount = (domain: PropertyDomain): number => {
  return getDomainFields(domain).length;
};

const getDomainRequiredCount = (domain: PropertyDomain): number => {
  return getDomainFields(domain).filter((field) => field.rules === 'required')
    .length;
};

const getDomainOptionalCount = (domain: PropertyDomain): number => {
  return getDomainFields(domain).filter((field) => field.rules !== 'required')
    .length;
};

const handleDomainChange = (domain: PropertyDomain) => {
  activeDomain.value = domain;
  selectedFieldId.value = '';
};

const selectField = (fieldId: string) => {
  selectedFieldId.value = fieldId;
};

const addField = () => {
  const newField: FieldSchema = {
    id: generateId(),
    fieldName: '',
    label: '',
    component: FieldComponent.INPUT,
    componentProps: {},
    domain: activeDomain.value,
    order: getDomainFieldCount(activeDomain.value),
    isActive: true,
  };

  multiDomainProperties.value.domains[activeDomain.value].schema.push(newField);
  selectField(newField.id);
  editField(
    multiDomainProperties.value.domains[activeDomain.value].schema.length - 1,
  );
};

const editField = (index: number) => {
  const fields = getDomainFields(activeDomain.value);
  const field = fields[index];

  if (!field) {
    message.error('字段不存在');
    return;
  }

  // 转换字段格式以适配FieldEditor组件
  editingField.value = {
    id: field.id,
    name: field.fieldName, // 将fieldName映射到name
    label: field.label,
    type: convertComponentToType(field.component), // 将component映射到type
    required: field.rules === 'required',
    defaultValue: field.defaultValue,
    options: field.componentProps?.options || [],
    validation: {
      minLength: field.validation?.minLength,
      maxLength: field.validation?.maxLength,
      min: field.validation?.minValue,
      max: field.validation?.maxValue,
      pattern: field.validation?.pattern || '',
      customRule: field.validation?.customRule || '',
    },
    uiConfig: {
      placeholder: field.componentProps?.placeholder || '',
      helpText: field.description || '',
      width: '',
      showLabel: true,
      layout: 'horizontal',
    },
  };
  fieldEditorVisible.value = true;
};

// 转换组件类型到字段类型
const convertComponentToType = (component: string): string => {
  const typeMap: Record<string, string> = {
    Input: 'STRING',
    InputNumber: 'NUMBER',
    Select: 'ENUM', // Select组件映射为ENUM类型，这样会显示选项配置;
    Switch: 'BOOLEAN',
    DatePicker: 'DATE',
    Textarea: 'TEXTAREA',
    Upload: 'FILE',
  };
  return typeMap[component] || 'STRING';
};

// 转换字段类型到组件类型
const convertTypeToComponent = (type: string): string => {
  const componentMap: Record<string, string> = {
    STRING: 'Input',
    NUMBER: 'InputNumber',
    ENUM: 'Select',
    BOOLEAN: 'Switch',
    DATE: 'DatePicker',
    TEXTAREA: 'Textarea',
    FILE: 'Upload',
  };
  return componentMap[type] || 'Input';
};

const updateField = (field: FieldSchema) => {
  const fields = multiDomainProperties.value.domains[activeDomain.value].schema;
  const index = fields.findIndex((f) => f.id === field.id);
  if (index !== -1) {
    fields[index] = { ...field };
  }
};

const updateEditingField = (field: any) => {
  const fields = multiDomainProperties.value.domains[activeDomain.value].schema;
  const index = fields.findIndex((f) => f.id === field.id);
  if (index !== -1) {
    // 转换回我们的字段格式
    const updatedField: FieldSchema = {
      id: field.id,
      fieldName: field.name, // 将name映射回fieldName
      label: field.label,
      component: convertTypeToComponent(field.type) as FieldComponent, // 将type映射回component
      componentProps: {
        placeholder: field.uiConfig?.placeholder || '',
        options: field.options || [],
        ...field.componentProps,
      },
      rules: field.required ? 'required' : undefined,
      defaultValue: field.defaultValue,
      domain: activeDomain.value,
      order: fields[index].order,
      isActive: true,
      validation: {
        minLength: field.validation?.minLength,
        maxLength: field.validation?.maxLength,
        minValue: field.validation?.min,
        maxValue: field.validation?.max,
        pattern: field.validation?.pattern,
        customRule: field.validation?.customRule,
      },
      description: field.uiConfig?.helpText,
      descriptiondescription,
    };
    fields[index] = updatedField;
  }
  fieldEditorVisible.value = false;
  editingField.value = null;
};

const removeField = (index: number) => {
  const field =
    multiDomainProperties.value.domains[activeDomain.value].schema[index];
  if (selectedFieldId.value === field.id) {
    selectedFieldId.value = '';
  }
  multiDomainProperties.value.domains[activeDomain.value].schema.splice(
    index,
    1,
  );
  updateMetadata();
};

const deleteSelectedField = () => {
  const fields = multiDomainProperties.value.domains[activeDomain.value].schema;
  const index = fields.findIndex((f) => f.id === selectedFieldId.value);
  if (index !== -1) {
    fields.splice(index, 1);
    selectedFieldId.value = '';
    updateMetadata();
  }
};

const previewDomainForm = () => {
  previewSchema.value = getDomainFields(activeDomain.value);
  previewData.value =
    multiDomainProperties.value.domains[activeDomain.value].data || {};
  previewVisible.value = true;
};

const handlePreviewFormChange = (values: Record<string, any>) => {
  console.log('预览表单数据变化:', values);
  multiDomainProperties.value.domains[activeDomain.value].data = values;
};

const saveAllDomains = async () => {
  saving.value = true;
  try {
    updateMetadata();
    await new Promise((resolve) => setTimeout(resolve, 1000));
    message.success('多领域属性保存成功');
    emit('properties-update', multiDomainProperties.value);
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

const exportConfig = () => {
  const data = JSON.stringify(multiDomainProperties.value, null, 2);
  const blob = new Blob([data], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `multi-domain-properties-${props.resourceId}.json`;
  a.click();
  URL.revokeObjectURL(url);
  message.success('配置导出成功');
};

const updateMetadata = () => {
  const totalFields = Object.values(multiDomainProperties.value.domains).reduce(
    (sum, domain) => sum + domain.schema.length,
    0,
  );

  multiDomainProperties.value.metadata.totalFields = totalFields;
  multiDomainProperties.value.metadata.lastModified = new Date().toISOString();
};

// 工具函数
const generateId = () => {
  return 'id_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

const getFieldTypeIcon = (component: string): string => {
  const iconMap: Record<string, string> = {
    Input: 'ant-design:edit-outlined',
    InputNumber: 'ant-design:number-outlined',
    Select: 'ant-design:down-outlined',
    Switch: 'ant-design:check-square-outlined',
    DatePicker: 'ant-design:calendar-outlined',
    Textarea: 'ant-design:file-text-outlined',
    Upload: 'ant-design:upload-outlined',
  };
  return iconMap[component] || 'ant-design:question-outlined';
};

const getFieldTypeColor = (component: string): string => {
  const colorMap: Record<string, string> = {
    Input: 'blue',
    InputNumber: 'green',
    Select: 'cyan',
    Switch: 'orange',
    DatePicker: 'purple',
    Textarea: 'geekblue',
    Upload: 'magenta',
  };
  return colorMap[component] || 'default';
};

const getFieldTypeName = (component: string): string => {
  const nameMap: Record<string, string> = {
    Input: '输入框',
    InputNumber: '数字输入框',
    Select: '选择器',
    Switch: '开关',
    DatePicker: '日期选择器',
    Textarea: '多行文本',
    Upload: '文件上传',
  };
  return nameMap[component] || '未知组件';
};

function getDefaultDomainConfig(domain: PropertyDomain): DomainConfig {
  const configs = {
    [PropertyDomain.BUSINESS]: {
      name: '业务领域',
      description: '核心业务属性，如价格、房型、设施等',
      icon: 'ant-design:shop-outlined',
      color: '#1890ff',
    },
    [PropertyDomain.OPERATION]: {
      name: '运营领域',
      description: '运营相关属性，如渠道、库存、合作方等',
      icon: 'ant-design:setting-outlined',
      color: '#52c41a',
    },
    [PropertyDomain.TECHNICAL]: {
      name: '技术领域',
      description: '技术相关属性，如版本、API、环境等',
      icon: 'ant-design:code-outlined',
      color: '#722ed1',
    },
    [PropertyDomain.COMPLIANCE]: {
      name: '合规风控',
      description: '合规和风控属性，如资质、状态、隐私等',
      icon: 'ant-design:safety-outlined',
      color: '#fa8c16',
    },
  };

  return {
    key: domain,
    ...configs[domain],
    visible: true,
    editable: true,
    required: false,
    order: Object.keys(configs).indexOf(domain),
  };
}
</script>

<style scoped>
.multi-domain-property-manager {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.manager-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.manager-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.domain-content {
  padding: 20px 0;
}

.domain-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 16px;
  margin-bottom: 24px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.domain-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.domain-info p {
  margin: 0 0 12px;
  font-size: 14px;
  color: #8c8c8c;
}

.domain-stats {
  display: flex;
  gap: 8px;
}

.domain-actions {
  display: flex;
  gap: 8px;
}

.fields-section {
  display: flex;
  gap: 24px;
  min-height: 400px;
}

.fields-list {
  flex: 0 0 350px;
  max-height: 500px;
  overflow-y: auto;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.field-item {
  padding: 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s;
}

.field-item:hover {
  background: #f5f5f5;
}

.field-item--selected {
  background: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.field-info {
  flex: 1;
}

.field-header {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 8px;
}

.field-name {
  flex: 1;
  font-weight: 500;
  color: #262626;
}

.field-details {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #8c8c8c;
}

.field-actions {
  display: flex;
  gap: 4px;
  margin-top: 8px;
}

.field-editor {
  flex: 1;
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}
</style>
